package com.appspot.gaeforum309.db;

import java.util.Date;
import java.util.List;

import javax.jdo.Query;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;

// TODO: Add a possibility to remove an user.
// The removing consiste of :
//   - Remove DBUser from database
//   - Set key as null on all his field.
//   - When a null user is referenced, user is named "removed user" (for example, author of a message)

/**
 * Class DBUser represent a user in database.
 * 
 * When a new user logger with Google account logged in forum, a new DBUser is created.
 * @author GAEForum Team
 */
@PersistenceCapable
public class DBUser {
	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
	
	/**
	 * It's the Google Account ID.
	 */
	@Persistent
	private String userId;

	/**
	 * Store the date of the first connexion on forum.
	 * It's not the date of creation of the Google Account, but in the forum.
	 */
	@Persistent
	private Date dateInscription;
	
	/**
	 * Store the date of the latest user connexion.
	 * This field make possible to detect user with no activity.
	 */
	@Persistent
	private Date dateLastLogin;
	
	/**
	 * It's the E-mail of user.
	 * The E-mail is provide by Google when user navigate on the forum.
	 * It's not possible to get email from userId directly, so we store it.
	 */
	@Persistent
	private String email;
	
	@Persistent
	private boolean firstLogin;
	
	public DBUser(String userId, String email) {
		super();
		this.userId = userId;
		this.email = email;
		
		this.dateInscription = new Date();
		this.dateLastLogin = new Date();
		this.firstLogin = true;
	}

	/**
	 * Get a DBUser from his userId.
	 * @param userId ID of the user.
	 * @return DBUser or null if user do not exist.
	 */
	public static DBUser getUserById(String userId)
	{
		Query q = PMF.pm().newQuery(DBUser.class);
		q.setFilter("userId == argUserId");
		q.declareParameters("String argUserId");
		@SuppressWarnings("unchecked")
		List<DBUser> res = (List<DBUser>) q.execute(userId);
		
		if(res.size() == 0)
			return null;
		else
			return res.get(0);
	}
	
	public static DBUser getUser(String keystr)
	{
		Key key = KeyFactory.stringToKey(keystr);
		if(key == null)
			return null;
		
		DBUser res = (DBUser)PMF.pm().getObjectById(DBUser.class, key);
		return res;
	}
	
	public static DBUser getUser(Key key)
	{
		if(key == null)
			return null;
		
		DBUser res = (DBUser)PMF.pm().getObjectById(DBUser.class, key);
		return res;
	}
	
	public boolean isFirstLogin()
	{
		return firstLogin;
	}
	
	public void userWelcome()
	{
		firstLogin = false;
	}
	
	/**
	 * Get the Key of the user in data base
	 * @return Key of user
	 */
	public Key getKey() {
		return key;
	}

	/**
	 * Get the userId
	 * @return userId
	 */
	public String getUserId() {
		return userId;
	}

	/**
	 * Get the date of the inscription.
	 * @return Date of the inscription
	 */
	public Date getDateInscription() {
		return dateInscription;
	}

	/**
	 * Get the date of the last login.
	 * 
	 * The date of the last login is automatically updated when user navigate on the forum.
	 * @return Date of the last login
	 */
	public Date getDateLastLogin() {
		return dateLastLogin;
	}

	/**
	 * Get the E-mail of the user.
	 * 
	 * The E-mail is provided by Google.
	 * @return E-mail of the user.
	 */
	public String getEmail() {
		return email;
	}

	/**
	 * This method is usefull when a user make a request on the forum, to update his DBUser record.
	 * 
	 * If user not in data base, his profile his created, else his profile is updated with most recent information.
	 * @param user current Google User
	 * @return DBUser of the current user
	 */
	public static DBUser createOrUpdateUser(User user)
	{
		DBUser dbuser;
		dbuser = getUserById(user.getUserId());
		
		if(dbuser == null)
		{
			dbuser = new DBUser(user.getUserId(), user.getEmail());
			
			PMF.pm().makePersistent(dbuser);
		}
		else
		{
			dbuser.dateLastLogin = new Date();
			dbuser.email = user.getEmail();
		}
		
		return dbuser;
	}
}

